﻿using System;
using System.Net;
using System.Windows;

using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Grids;
using VAdvantage.Classes;
using VAdvantage.Model;
using System.Collections.Generic;
//using C1.Silverlight.DataGrid;
//using C1.Silverlight.DataGrid.Data;
using System.Collections;
using VAdvantage.DataBase;
using System.Windows.Controls;
using System.Windows.Data;
using System.Linq;


namespace VAdvantage.Controls
{

    public class VDataGrid : DataGrid
    {
        #region
        private bool _showRowNumber = false;

        private GridTable tableObj;

        public event EventHandler CurrentCellDirtyStateChanged;

        public event EventHandler DelyedCellEditEnd;

        public VDataGrid()
        {
            BindingExpression bx = this.GetBindingExpression(DataGrid.ItemsSourceProperty);
        }

        public bool ShowRowNumber
        {
            get
            {
                return _showRowNumber;
            }
            set
            {
                _showRowNumber = value;
            }
        }

        public bool isCellinEditMode = false;

        SolidColorBrush _backgroundBrush = new SolidColorBrush(Colors.White);

        private bool isCellValueChanged = false;

        #endregion

        private bool _paintRow = false;
        public bool SupressRowPaint
        {
            set
            {
                _paintRow = value;
            }
        }

        public bool IsMiniGrid { get; set; }


        protected override void OnLoadingRow(DataGridRowEventArgs e)
        {
            base.OnLoadingRow(e);

            if (_showRowNumber && (HeadersVisibility == DataGridHeadersVisibility.Row || HeadersVisibility == DataGridHeadersVisibility.All))
            {

                e.Row.Header = e.Row.GetIndex() + 1;
            }

                PaintRow(e.Row);
        }

        public void PaintRow(DataGridRow dataRow)
        {
            
            if (_paintRow)
            {
                return;
            }

            if (_showRowNumber && (HeadersVisibility == DataGridHeadersVisibility.Row || HeadersVisibility == DataGridHeadersVisibility.All))
            {

                dataRow.Header = dataRow.GetIndex() + 1;
            }

            if (dataRow.Background == null)
            {
                dataRow.Background = new SolidColorBrush(Colors.Transparent);
            }


            if (!IsCellEditable(dataRow.GetIndex(), 0)) //_isActiveIndex != -1)
            {
                //_backgroundBrush.Color =   GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                //dataRow.Background = new SolidColorBrush(GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR);
                ((SolidColorBrush)dataRow.Background).Color = GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;// Colors.Transparent;
            }
            else
            {
               // if (dataRow.GetIndex() % 2 == 0)
               // {
                    // _backgroundBrush.Color =   GlobalVariable.GRID_DEFAULTBACK_COLOR;
                    ((SolidColorBrush)dataRow.Background).Color = Colors.Transparent;

              //  }
               // else
               // {
                    //_backgroundBrush.Color = GlobalVariable.GRID_DEFAULTALTERNATEBACK_COLOR;
                    //((SolidColorBrush)dataRow.Background).Color = GlobalVariable.GRID_DEFAULTALTERNATEBACK_COLOR;
                //}

                //foreach (DataGridViewCell cell in this.Rows[row].Cells)
                //{
                //    if (cell.ReadOnly && cell.OwningColumn.ReadOnly)
                //    {
                //        cell.Style.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                //    }
                //    else if (row % 2 == 0)
                //    {
                //        cell.Style.BackColor = DataBase.GlobalVariable.GRID_DEFAULTBACK_COLOR;
                //    }
                //    else
                //    {
                //        cell.Style.BackColor = DataBase.GlobalVariable.GRID_DEFAULTALTERNATEBACK_COLOR;
                //    }
                //}
            }
        }

       

        protected override void OnBeginningEdit(DataGridBeginningEditEventArgs e)
        {
            if (tableObj != null)
            {
                IDataGridColumn col = (IDataGridColumn)e.Column;

                if (!tableObj.IsInserting() && col.ReadOnly)
                {
                    e.Cancel = true;
                }

                else
                {

                    GridField field = col.Field; // .Column.  CurrentCell.OwningColumn.Name);
                    if (!field.IsEditable(true))//|| _headerClicked)
                    {
                        //CurrentCell.ReadOnly = true;
                        e.Cancel = true;
                        //return;
                    }

                }
                //cellMouseDown = false;
            }
            base.OnBeginningEdit(e);
        }

        protected override void OnPreparingCellForEdit(DataGridPreparingCellForEditEventArgs e)
        {
            base.OnPreparingCellForEdit(e);
            isCellinEditMode = true;
        }




        //protected override void OnCellEditEnding(DataGridCellEditEndingEventArgs e)
        //{

        //    base.OnCellEditEnding(e);
        //}

        protected override void OnCellEditEnded(DataGridCellEditEndedEventArgs e)
        {
            if (isCellValueChanged)
            {
                PaintRow(e.Row);
            }
            base.OnCellEditEnded(e);
            isCellinEditMode = false;
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {

            base.OnMouseLeftButtonDown(e);
            //FrameworkElement fe = (FrameworkElement)e.OriginalSource;
            // DataGridColumn column = (DataGridColumn)DataGridColumn.GetColumnContainingElement(fe);
            // if (column != null && column is ICustomSortColumn)
            // {
            //     column.CanUserSort = false;
            //     //VisualStateManager.GoToState(this, "SortAscending", true);
            // }



        }

        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonUp(e);
        }


        private int _indexKeyColumn = -1;
        /** Index of Color Column               */
        private int _indexColorColumn = -1;
        /** Index of Processed Column           */
        private int _indexProcessedColumn = -1;
        /** Index of IsActive Column            */
        private int _indexActiveColumn = -1;
        /** Index of AD_Client_ID Column        */
        private int _indexClientColumn = -1;
        /** Index of AD_Org_ID Column           */
        private int _indexOrgColumn = -1;

        private void SetColumnIndex(List<GridField> lst)
        {

            for (int i = 0; i < lst.Count; i++)
            {

                GridField field = lst[i];
                if (field.IsKey())
                    _indexKeyColumn = i;
                else if (field.GetColumnName().Equals("IsActive"))
                    _indexActiveColumn = i;
                else if (field.GetColumnName().Equals("Processed"))
                    _indexProcessedColumn = i;
                else if (field.GetColumnName().Equals("AD_Client_ID"))
                    _indexClientColumn = i;
                else if (field.GetColumnName().Equals("AD_Org_ID"))
                    _indexOrgColumn = i;
            }
        }

        /// <summary>
        /// Add columns to GridView 
        /// </summary>
        /// <param name="frm">parent control</param>
        /// <param name="mTab">gridtab object</param>
        /// <returns>no of column added</returns>
        public int SetupGridTable(Apps.APanel frm, GridTab mTab)
        {
            this.AutoGenerateColumns = false;
            if (!mTab.IsDisplayed(true))
                return 0;
            tableObj = mTab.GetTableObj();
            int size = mTab.GetFieldCount();

            List<GridField> gridFields = new List<GridField>(tableObj.GetFieldList());

            gridFields.Sort((x, y) => x.GetMRSeqNo().CompareTo(y.GetMRSeqNo()));

            // SetColumnIndex(gridFields);

            int i = -1;
            foreach (GridField mField in gridFields)
            {

                //GridField mField = gridFields[i];
                if (mField == null)
                    continue;

                ++i;
                if (mField.IsKey())
                    _indexKeyColumn = i;
                else if (mField.GetColumnName().Equals("IsActive"))
                    _indexActiveColumn = i;
                else if (mField.GetColumnName().Equals("Processed"))
                    _indexProcessedColumn = i;
                else if (mField.GetColumnName().Equals("AD_Client_ID"))
                    _indexClientColumn = i;
                else if (mField.GetColumnName().Equals("AD_Org_ID"))
                    _indexOrgColumn = i;




                bool isDisplayed = mField.IsDisplayed();

                //int displayType = ctrl.DisplayType;
                string columnName = mField.GetColumnName();
                bool mandatory = mField.IsMandatory(false);      //  no context check
                bool readOnly = mField.IsReadOnly();
                bool updateable = mField.IsEditable(false);      //  no context check
                //int WindowNo = mField.getWindowNo();
                int displayType = mField.GetDisplayType();
                //  Not a Field
                if (mField.IsHeading())
                    continue;

                //	String (clear/password)
                if (displayType == DisplayType.String
                    || displayType == DisplayType.Text || displayType == DisplayType.TextLong
                    || displayType == DisplayType.Memo)
                {

                    VDataGridTextColumn gdtxt = new VDataGridTextColumn();
                    //gdtxt.Binding = new System.Windows.Data.Binding(columnName.ToUpper());
                    gdtxt.Header = mField.GetHeader();
                    //gdtxt.MaxInputLength = (mField.GetFieldLength() > 60) ? 60 : mField.GetFieldLength();
                    gdtxt.DataPropertyName = columnName.ToUpper();
                    gdtxt.DataGridView = this;

                    gdtxt.Field = mField;
                    if (readOnly || !updateable)
                    {
                        gdtxt.ReadOnly = true;
                        //gdtxt.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;


                    }
                    //gdtxt.Width = DataGridLength.SizeToCells;// Math.Max(mField.GetDisplayLength(), 100);
                    this.Columns.Add(gdtxt);
                    gdtxt.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }


                else if (displayType == DisplayType.URL)
                {

                    VDataGridURLColumn gdtxt = new VDataGridURLColumn();
                    //gdtxt.Binding = new System.Windows.Data.Binding(columnName.ToUpper());
                    gdtxt.Header = mField.GetHeader();
                    //gdtxt.MaxInputLength = (mField.GetFieldLength() > 60) ? 60 : mField.GetFieldLength();
                    gdtxt.DataPropertyName = columnName.ToUpper();
                    gdtxt.DataGridView = this;

                    gdtxt.Field = mField;
                    if (readOnly || !updateable)
                    {
                        gdtxt.ReadOnly = true;
                        //gdtxt.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    //gdtxt.Width = DataGridLength.SizeToCells;// Math.Max(mField.GetDisplayLength(), 100);
                    this.Columns.Add(gdtxt);
                    gdtxt.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }

                //else if (displayType == DisplayType.PrinterName)
                //{
                //Grids.VPrinterColumn gdtxt = new Grids.VPrinterColumn();
                //gdtxt.DataPropertyName = columnName;
                //gdtxt.Name = columnName;
                //gdtxt.HeaderText = mField.GetHeader();
                //gdtxt.Field = mField;
                //if (readOnly || !updateable)
                //{
                //    gdtxt.ReadOnly = true;
                //    gdtxt.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                //}
                //gdtxt.Width = 100;
                //this.Columns.Add(gdtxt);
                //gdtxt.Visible = isDisplayed;
                //}
                //	URL



                //	File Path / Name
                else if (displayType == DisplayType.FilePath || displayType == DisplayType.FileName)
                {
                    VDataGridFileColumn file = new VDataGridFileColumn();

                    file.Header = mField.GetHeader();
                    file.DataPropertyName = columnName.ToUpper();

                    file.Field = mField;
                    file.DataGridView = this;

                    if (readOnly || !updateable)
                    {
                        file.ReadOnly = true;
                        //file.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    //file.Width = DataGridLength.SizeToHeader;

                    this.Columns.Add(file);


                    file.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }

                //	Number
                else if (DisplayType.IsNumeric(displayType))
                {
                    VDataGridNumericColumn gdtx = new VDataGridNumericColumn();
                    // gdtx.DefaultCellStyle.Format = DisplayType.GetNumberFormat(displayType).GetFormat();
                    //DataGridViewCellStyle style = new DataGridViewCellStyle();
                    //style.Format = "N2";
                    if (displayType == DisplayType.Integer)
                    {
                        //gdtx.DefaultCellStyle.Format = "N0";
                    }
                    else
                    {
                        //gdtx.DefaultCellStyle.Format = "N2";
                    }
                    gdtx.DataPropertyName = columnName.ToUpper();
                    gdtx.Header = mField.GetHeader();
                    //gdtx.HeaderText = mField.GetHeader();
                    // gdtx.Width = Math.Max(mField.GetDisplayLength(), 100);
                    gdtx.Field = mField;
                    if (readOnly || !updateable)
                    {
                        gdtx.ReadOnly = true;
                        //gdtx.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }

                    //gdtx.Width = DataGridLength.SizeToCells;

                    this.Columns.Add(gdtx);
                    gdtx.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    gdtx.DataGridView = this;
                }
                //	YesNo
                else if (displayType == DisplayType.YesNo)
                {
                    VDataGridCheckBoxColumn grdChk = new VDataGridCheckBoxColumn();

                    //grdChk.FlatStyle = FlatStyle.Popup;
                    //grdChk.Name = columnName;
                    grdChk.Header = mField.GetHeader();
                    //grdChk. .FalseValue = "False";
                    //grdChk.TrueValue = "True";
                    //grdChk.Width = Math.Max(mField.GetDisplayLength(), 100);
                    grdChk.DataPropertyName = columnName.ToUpper();
                    grdChk.DataGridView = this;
                    grdChk.Field = mField;
                    if (readOnly || !updateable)
                    {
                        grdChk.ReadOnly = true;
                        //grdChk.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    this.Columns.Add(grdChk);

                    //}
                    grdChk.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }

                    //	Lookup
                else if (DisplayType.IsLookup(displayType) || displayType == DisplayType.ID)
                {
                    Lookup lookup = mField.GetLookup();

                    ////for search and parents column

                    if (displayType != DisplayType.Search)
                    {
                        //edit vcontrol combobox (dynamic validation)
                        //normal state--->TextBox
                        //edit control --->Combobox
                        VDataGridComboBoxColumn vtc = new VDataGridComboBoxColumn();
                        vtc.Header = mField.GetHeader();
                        //vtc.Name = columnName;
                        vtc.Field = mField;

                        vtc.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                        vtc.DataPropertyName = columnName.ToUpper();

                        // vtc.Field = mField;
                        if (readOnly || !updateable || lookup == null)
                        {
                            vtc.ReadOnly = true;
                            //vtc.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                        }
                        //vtc.Width = DataGridLength.SizeToHeader;

                        this.Columns.Add(vtc);
                        vtc.DataGridView = this;
                        //vtc.Visible = isDisplayed;
                    }

                    else
                    {
                        VDataGridTextButtonColumn grdLoc = new VDataGridTextButtonColumn();
                        grdLoc.DataPropertyName = columnName.ToUpper();
                        grdLoc.Header = mField.GetHeader();
                        grdLoc.Field = mField;
                        if (readOnly || !updateable || lookup == null)
                        {
                            grdLoc.ReadOnly = true;
                            //grdLoc.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                        }
                        //grdLoc.Image = VAdvantage.Properties.Resources.Assignment24;
                        //grdLoc.Width = DataGridLength.SizeToHeader;// Math.Max(mField.GetDisplayLength(), 100);
                        grdLoc.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                        this.Columns.Add(grdLoc);
                        grdLoc.DataGridView = this;
                        if (isDisplayed)
                        {
                            // specialCaseHandleColList.Add(grdLoc);
                        }
                    }
                }

            //Date /////////
                else if (DisplayType.IsDate(displayType))
                {


                    VDataGridDateTimeColumn grdDate = new VDataGridDateTimeColumn();

                    grdDate.DataPropertyName = columnName;
                    //grdDate.Name = columnName;
                    grdDate.Header = mField.GetHeader();
                    grdDate.Field = mField;

                    grdDate.DataGridView = this;

                    //if (displayType == DisplayType.Date)
                    //{
                    //    grdDate.CellStyle.TargetType.fo .DefaultCellStyle.Format = "d";
                    //}
                    //else
                    //    if (displayType == DisplayType.Time)
                    //    {
                    //        grdDate.DefaultCellStyle.Format = "T";
                    //    }
                    //    else
                    //    {
                    //        grdDate.DefaultCellStyle.Format = "G";
                    //    }


                    //grdDate.Width = Math.Max(mField.GetDisplayLength(), 100);
                    if (readOnly || !updateable)
                    {
                        grdDate.ReadOnly = true;
                        //grdDate.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    this.Columns.Add(grdDate);
                    grdDate.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }
                else if (displayType == DisplayType.Location || displayType == DisplayType.Locator)
                {
                    VDataGridTextButtonColumn grdLoc = new VDataGridTextButtonColumn();
                    grdLoc.DataPropertyName = columnName.ToUpper();
                    grdLoc.Header = mField.GetHeader();
                    grdLoc.Field = mField;
                    //grdLoc.Width = DataGridLength.SizeToHeader;// Math.Max(mField.GetDisplayLength(), 100);
                    if (readOnly || !updateable)
                    {
                        grdLoc.ReadOnly = true;
                        //grdLoc.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    grdLoc.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    this.Columns.Add(grdLoc);

                    grdLoc.DataGridView = this;

                }

                else if (displayType == DisplayType.Account)
                {
                    VDataGridAccountColumn grdLoc = new VDataGridAccountColumn();
                    grdLoc.DataPropertyName = columnName.ToUpper();
                    grdLoc.Header = mField.GetHeader();
                    grdLoc.Field = mField;
                    //grdLoc.Width = DataGridLength.SizeToHeader;// Math.Max(mField.GetDisplayLength(), 100);
                    if (readOnly || !updateable)
                    {
                        grdLoc.ReadOnly = true;
                        //grdLoc.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    grdLoc.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    this.Columns.Add(grdLoc);
                    grdLoc.DataGridView = this;
                }

                else if (displayType == DisplayType.PAttribute)
                {
                    VDataGridPAttributeColumn grdAttr = new VDataGridPAttributeColumn();
                    grdAttr.DataPropertyName = columnName.ToUpper();

                    grdAttr.Header = mField.GetHeader();
                    grdAttr.Field = mField;
                    // grdAttr.Width = Math.Max(mField.GetDisplayLength(), 100);
                    if (readOnly || !updateable)
                    {
                        grdAttr.ReadOnly = true;
                        //grdAttr.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    grdAttr.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    this.Columns.Add(grdAttr);
                    grdAttr.DataGridView = this;
                }



                else if (displayType == DisplayType.Button)
                {
                    VDataGridButtonColumn grdBtn = new VDataGridButtonColumn();
                    grdBtn.Field = mField;
                    grdBtn.Header = mField.GetHeader();

                    if (readOnly || !updateable)
                    {
                        grdBtn.ReadOnly = true;
                        //grdBtn.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    grdBtn.DataPropertyName = columnName;

                    grdBtn.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    if (frm != null)
                    {
                        grdBtn.Button_Click += frm.btn_click;
                    }
                    this.Columns.Add(grdBtn);
                }

               // else if (displayType == DisplayType.Assignment)
                //{
                ////DataGridViewButtonColumn grdBtn = new DataGridViewButtonColumn();
                //VAssignmentColumn grdAsmnt = new VAssignmentColumn();
                //grdAsmnt.Name = columnName;
                ////grdBtn.UseColumnTextForButtonValue = true;
                //grdAsmnt.Field = mField;
                //grdAsmnt.HeaderText = mField.GetHeader();
                //grdAsmnt.Width = 100;// Math.Max(mField.GetDisplayLength(), 100);
                //grdAsmnt.Visible = isDisplayed;
                //if (readOnly || !updateable)
                //{
                //    grdAsmnt.ReadOnly = true;
                //    grdAsmnt.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                //}
                //grdAsmnt.DataPropertyName = columnName;
                //this.Columns.Add(grdAsmnt);

                //}

                else if (displayType == DisplayType.Image)
                {
                    VDataGridImageColumn gdtxt = new VDataGridImageColumn();
                    gdtxt.DataPropertyName = columnName.ToUpper();

                    gdtxt.Header = mField.GetHeader();
                    gdtxt.Field = mField;
                    gdtxt.DataGridView = this;

                    if (readOnly || !updateable)
                    {
                        gdtxt.ReadOnly = true;
                        //gdtxt.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }
                    //gdtxt.MaxInputLength = (mField.GetDisplayLength() > 60) ? 60 : mField.GetDisplayLength();
                    this.Columns.Add(gdtxt);
                    gdtxt.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }



               // else if (displayType == DisplayType.Color)
                //{
                //DataGridViewTextBoxColumn gdtxt = new DataGridViewTextBoxColumn();
                //gdtxt.DataPropertyName = columnName;
                //gdtxt.Name = columnName;
                //gdtxt.HeaderText = "*" + mField.GetHeader();
                //if (readOnly || !updateable)
                //{
                //    gdtxt.ReadOnly = true;
                //    gdtxt.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                //}
                //gdtxt.MaxInputLength = (mField.GetDisplayLength() > 60) ? 60 : mField.GetDisplayLength();
                //this.Columns.Add(gdtxt);
                //gdtxt.Visible = isDisplayed;
                //}

                ////  Assignment
                //else if (displayType == DisplayType.Assignment)
                //{
                //    VAssignment assign = new VAssignment (mandatory, readOnly, updateable);
                //    assign.setName(columnName);
                //    assign.setField (mField);
                //    editor = assign;
                //}

                //  Color
                //else if (displayType == DisplayType.Color)
                //{
                //    VColor color = new VColor (mTab, mandatory, readOnly);
                //    color.setName(columnName);
                //    color.setField (mField);
                //    editor = color;
                //}

                //  Image
                //else if (displayType == DisplayType.Image)
                //{
                //    VImage image = new VImage (columnName, WindowNo);
                //    image.setName(columnName);
                //    image.setField (mField);
                //    editor = image;
                //}



                     ////	Memo (single row)
                //else if (displayType == DisplayType.Memo)
                //{
                //    VMemo vt = new VMemo(columnName, mandatory, readOnly, updateable,
                //        mField.getDisplayLength(), mField.getFieldLength());
                //    vt.setName(columnName);
                //    vt.setField (mField);
                //    editor = vt;
                //}


                //  Long Text (CLob)

                else if (DisplayType.IsLOB(displayType))
                {
                    VDataGridLobColumn lob = new VDataGridLobColumn();
                    lob.DataPropertyName = columnName.ToUpper();
                    lob.Header = mField.GetHeader();
                    lob.Field = mField;
                    lob.DataGridView = this;
                    if (readOnly || !updateable)
                    {
                        lob.ReadOnly = true;
                        //lob.DefaultCellStyle.BackColor = DataBase.GlobalVariable.GRID_DEFAULTDISABLEBACK_COLOR;
                    }

                    this.Columns.Add(lob);
                    lob.Visibility = isDisplayed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                }
                ////  Binary (BLob)

                else
                {
                    DataGridTextColumn txt = new DataGridTextColumn();

                    txt.Binding = new Binding(columnName.ToUpper());
                    this.Columns.Add(txt);
                    txt.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            if (frm != null)
            {
                this.CurrentCellDirtyStateChanged += new EventHandler(frm.CurrentCellDirtyStateChanged);
                //this.DataError += new DataGridViewDataErrorEventHandler(frm.DataError);
            }
            return size;
        }

        public void RaiseCellValueChanged(object sender)
        {

            if (CurrentCellDirtyStateChanged != null)
            {
                CurrentCellDirtyStateChanged(sender, EventArgs.Empty);
            }
            isCellValueChanged = true;

            if (!isCellinEditMode)
            {
                if (DelyedCellEditEnd != null)
                {
                    DelyedCellEditEnd(sender, EventArgs.Empty);
                }
            }
        }

        /// <summary>
        /// IS Cell Editable or Not
        /// </summary>
        /// <param name="row">row number</param>
        /// <param name="col">col number</param>
        /// <returns>true if editable</returns>
        public bool IsCellEditable(int row, int col)
        {
            //	//log.fine( "MTable.isCellEditable - Row=" + row + ", Col=" + col);
            //	Make Rows selectable
            //	if (col == 0)
            //		return true;

            //	Entire Table not editable
            if (this.IsReadOnly)
                return false;
            //	Key not editable
            //if (col ==    _indexKeyColumn)
            //  return false;

            /** @todo check link columns */

            //	Check column range
            //if (col < 0 && col >= m_fields.size())
            //  return false;
            //  IsActive Column always editable if no processed exists
            if (col == _indexActiveColumn && _indexProcessedColumn == -1)
                return true;
            //	Row
            if (!IsRowEditable(row))
                return false;

            return true;
            // return ((GridField)m_fields.get(col)).isEditable(false);
        }	//	IsCellEditable

        /// <summary>
        /// Is Current Row Editable
        /// </summary>
        /// <param name="row">row number</param>
        /// <returns>true if editable</returns>
        public bool IsRowEditable(int row)
        {
            //	//log.fine( "MTable.isRowEditable - Row=" + row);
            //	Entire Table not editable or no row
            if (IsReadOnly || row < 0)
                return false;
            //	If not Active - not editable
            if (_indexActiveColumn > 0)		//	&& m_TabNo != Find.s_TabNo)
            {
                //Object value = GetCellValue(this.Rows[row], _indexActiveColumn);
                Object value = GetCellValue(row, _indexActiveColumn);
                if (!"True".Equals(value))// instanceof Boolean)
                {
                    //if (!((Boolean)value).booleanValue())
                    return false;
                }
                else if ("N".Equals(value))
                    return false;
            }
            //	If Processed - not editable (Find always editable)
            if (_indexProcessedColumn > 0)		//	&& m_TabNo != Find.s_TabNo)
            {
                //Object processed = GetCellValue(this.Rows[row], _indexProcessedColumn);
                Object processed = GetCellValue(row, _indexProcessedColumn);
                if ("True".Equals(processed))// instanceof Boolean)
                {
                    //if (((Boolean)processed).booleanValue())
                    return false;
                }
                else if ("Y".Equals(processed))
                    return false;
            }



            //
            //int[] co = GetClientOrgRecordID(this.Rows[row]);
            int[] co = GetClientOrgRecordID(row);
            int AD_Client_ID = co[0];
            int AD_Org_ID = co[1];
            int Record_ID = co[2];

            return MRole.GetDefault(Utility.Envs.GetCtx(), false).CanUpdate
                   (AD_Client_ID, AD_Org_ID, tableObj.GetTableID(), Record_ID, false);

        }

        //	isRowEditable
        /// <summary>
        /// get Client and org id's
        /// </summary>
        /// <param name="row">row number</param>
        /// <returns>int array</returns>
        private int[] GetClientOrgRecordID(int row)
        {
            int AD_Client_ID = -1;
            if (_indexClientColumn != -1)
            {
                object ii = GetCellValue(row, _indexClientColumn);//].Value;
                if (ii != null && ii != DBNull.Value)
                    AD_Client_ID = Convert.ToInt32(ii);
            }
            int AD_Org_ID = 0;
            if (_indexOrgColumn != -1)
            {
                object ii = GetCellValue(row, _indexOrgColumn);
                if (ii != null && ii != DBNull.Value)
                    AD_Org_ID = Convert.ToInt32(ii);
            }
            int Record_ID = 0;
            if (_indexKeyColumn != -1)
            {
                object ii = GetCellValue(row, _indexKeyColumn);
                if (ii != null && ii != DBNull.Value)
                    try
                    {
                        Record_ID = Convert.ToInt32(ii);
                    }
                    catch
                    {
                        // Logging.VLogger.Get().Config("Ivalid Format");
                    }
            }

            return new int[] { AD_Client_ID, AD_Org_ID, Record_ID };
        }

        private IEnumerable Rows
        {
            get
            {
                return this.ItemsSource as IEnumerable;
            }
        }

        private object GetCellValue(int row, int index)
        {
            object dataObject = (this.ItemsSource as BindingSource)[row];

            //if (this.Rows is IList)
            //{

            //}

            string colName = ((IDataGridColumn)this.Columns[index]).DataPropertyName;

            return ((DataUtil.DataObject)dataObject).GetFieldValue(colName);

        }

        public bool IsCellValuechanged
        {
            get
            {
                return isCellValueChanged;
            }
            set
            {
                isCellValueChanged = value;
            }
        }

        internal void PaintRow()
        {
            if (_paintRow)
                return;


            BindingSource rowSource = this.ItemsSource as BindingSource;
            for (int i = 0; i < rowSource.Count; i++)
            {
                DataUtil.DataObject obj = (DataUtil.DataObject)rowSource[i];
                
                FrameworkElement el =this.Columns.Last().GetCellContent(obj);


                if (el == null)
                {
                    ;
                }
                else
                {
                    DataGridRow row1 = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);
                    if (row1 != null)
                    {
                        PaintRow(row1);
                    }
                }
            }
        }

        internal void PaintRow(object data)
        {
            if (data != null)
            {
                DataUtil.DataObject obj = (DataUtil.DataObject)data;
                FrameworkElement el = this.Columns.Last().GetCellContent(obj);
                if (el == null)
                {
                    ;
                }
                else
                {
                    DataGridRow row1 = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);
                    if (row1 != null)
                    {
                        PaintRow(row1);
                    }
                }
            }
        }
    }
}
